package pe.com.nextel.util; // Generated package name

import com.mot.iden.device.StatusManager;
import java.io.IOException;
import java.io.InputStream;
import com.motorola.iden.security.MessageDigest;
import com.motorola.iden.security.NoSuchAlgorithmException;

/**
 * Utilities for manipulating strings.
 *
 * @author Glen Cordrey
 * @author eespinoza
 * @version 1.1 30/11/2007
 * @see 1.0
 */
public class StringUtils {
    
    public final static char HUNDREDS_DELIMITER = ',';
    public final static int CARACTER_PX = 7;
    
    /**
     * Creates a new <code>StringUtils</code> instance.
     *
     */
    private StringUtils() { /* all methods are static */
        
    } // constructor
    
    /** Removes all of the given character from the given StringBuffer.
     * @param buff A StringBuffer to be operated on.  The change in this buffer
     * will be persistent after this function call.
     * @param ch A character to be repeatly deleated from the giving
     * StringBuffer.
     */
    public static void remove(StringBuffer buff, char ch) {
        for (int i = 0; i < buff.length(); i++) {
            if (buff.charAt(i) == ch) {
                buff.deleteCharAt(i);
            }
        }
    }
    
    /**
     * Given a string and a delimiter, returns a Vector of Strings
     * broken up by the delimiter.
     * Note that the delimiter is not removed.
     * Returns an empty Vector if the delimiter is not found.
     * @param parseString String to parse
     * @param delimiter The delimiter
     * @return A List of Strings broken up by the delimiter.
     */
    public static List tokenize(String parseString, String delimiter) {
        List v = new ArrayList();
        int pos = 0;
        while (parseString.indexOf(delimiter, pos) != -1) {
            int curPos = parseString.indexOf(delimiter, pos);
            v.add(parseString.substring(pos, curPos + delimiter.length() - 1));
            pos = curPos + delimiter.length();
        }
        if (!"".equals(parseString.substring(pos))) {
            v.add(parseString.substring(pos));
        }
        return v;
    }
    
    /**
     * Given a string and a tamanio, returns a Vector of Strings
     * broken up by the delimiter.
     * Note that the delimiter is not removed.
     * Returns an empty Vector if the delimiter is not found.
     * @param parseString String to parse
     * @param tamanio The delimiter
     * @return A List of Strings broken up by the delimiter.
     */
    public static List tokenize(String parseString, int tamanio) {
        List lista = new ArrayList();
        tokenize(lista, parseString, tamanio);
        return lista;
    }
    
    public static void tokenize(List lista, String parseString, int tamanio) {
        
        while (parseString != null && parseString.length() > tamanio && tamanio > 0) {
            lista.add(parseString.substring(0, tamanio));
            parseString = parseString.substring(tamanio);
        }
        
        lista.add(parseString);
    }
    
    public static List tokenize(String parseString, String delimiter, int tamanio) {
        List lstResult = new ArrayList();
        List lista = tokenize(parseString, delimiter);
        for (Iterator it = lista.iterator(); it.hasNext();) {
            String str = (String) it.next();
            tokenize(lstResult, str, tamanio);
        }
        
        return lstResult;
    }
    
    /**
     * Divide la cadena label de acuerdo al parametro width
     * @param label cadena a dividir
     * @param width tamanio de las cadenas
     * @return List
     */
    public static List getListLabel(String label, int width) {
        
        return StringUtils.tokenize(label, "\n", width / CARACTER_PX);
    }
    
    /**
     * Convierte la cadena a short si @val es nulo o vacio retorna 0
     * @val cadena a convertir
     * @retun Un short
     */
    public static short stringToShort(String val) {
        return (val != null && !"".equals(val)) ? Short.parseShort(val) : 0;
    }
    
    /**
     * remplaza la cadena
     * char old
     * char new1
     * @return cadena convertida
     */
    public static String replace(String cad, char old, char newl) {
        if (cad == null) {
            cad = "";
        }
        return cad.replace(old, newl);
    }
    
    /**
     * Convierte la cadena null a vacio
     * @param cad cadena a transformar
     * @return cadena vacia si es null
     */
    public static String stringNullToBlank(String cad) {
        return cad != null ? cad : "";
    }
    
    public static char parseChar(String cad) {
        return (cad != null && cad.length() > 0) ? cad.charAt(0) : ' ';
    }
    
    public static boolean withSignal() {
        return (StatusManager.isRegistered(StatusManager.PD_REGISTRATION) && StatusManager.getStatus(StatusManager.SIGNAL_STRENGTH) > 0);
      
    }
    
    public static String leerInput(InputStream in) throws IOException {
        StringBuffer sbRespuesta = new StringBuffer();
        try {
            
            
            byte[] arrByte = new byte[1024];
            
            int len;
            while ((len = in.read(arrByte)) != -1) {
                sbRespuesta.append(new String(arrByte, 0, len));
            }
            System.out.println(sbRespuesta.toString());
            return sbRespuesta.toString();
            
        } finally {
            sbRespuesta.setLength(0);
            sbRespuesta = null;
            //aqui se comeno el system.gc
            System.gc();
            
        }
    }
    
    public static byte[] parsearInput(InputStream in) throws IOException {
        System.out.println("parsearInput");
        
        StringBuffer sbRespuesta = new StringBuffer();
        try {
            
            
            byte[] arrByte = new byte[1024];
            
            int len;
            //    System.out.println("1");
            while ((len = in.read(arrByte)) != -1) {
                sbRespuesta.append(new String(arrByte, 0, len));
            }
            // System.out.println("2");
            System.out.println(sbRespuesta.toString());
            // System.out.println("3");
            return sbRespuesta.toString().getBytes();
            
        } finally {
            sbRespuesta.setLength(0);
            sbRespuesta = null;
            //aqui se comeno el system.gc
            System.gc();
        }
    }
    
    public static void getStaticsMemoria() {
        
        //System.out.println("totalMemory =" + (Runtime.getRuntime().totalMemory()/1024) +" kb" );
        // System.out.println("freeMemory =" + (Runtime.getRuntime().freeMemory()/1024) +" kb" );
//        System.out.println("useMemory =" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024) + " kb");
//aqui se comeno el system.gc
        System.gc();
    }
    
        /**
         * Quita los ceros de la cadena por la derecha
         */
        public static String quitarCerosIzquierda(String cadena) {

            if (cadena == null) {
                return null;
            }
            StringBuffer retCad = new StringBuffer();

            char[] arryCad = cadena.toCharArray();

            byte flag = 0;

            for (int i = 0; i < cadena.length(); i++) {

                if (!(arryCad[i] == '0' && flag == 0)) {
                    flag = 1;

                    retCad.append(arryCad[i]);
                }
            }

            return retCad.toString();

        }
    
    
    public static String convertirSHA1(String data) {
        try {

            String datHex="";
            MessageDigest md = MessageDigest.getInstance("SHA");

            byte [] arreglo_data = data.getBytes();
            
            md.update(arreglo_data, 0, arreglo_data.length);
            byte[] digest = md.digest();
            for (int i=0; i<digest.length; i++) {
                String hex = Integer.toHexString(digest[i]);
                if (hex.length() == 1) hex = "0" + hex;
                hex=hex.substring(hex.length()-2);
                datHex= datHex + hex;
                
            }
            return datHex.toString();
            
        } catch(NoSuchAlgorithmException ex) {
            return "";
        }
        
    }
}// StringUtils






